<template>
  <!-- ============================================用户管理====================================== -->
  <el-container>
    <el-header style="height: 40px;padding-right: 10px;">
      <div style="display: flex;align-items: center;height: 40px;">
        <div style="flex-grow:1;font-size: 16px;font-weight: bold;">
          <el-breadcrumb :separator-icon="ArrowRight">
            <el-breadcrumb-item v-for="(item, index) in breadcrumb" :key="index">{{ item }}</el-breadcrumb-item>
          </el-breadcrumb>
        </div>
        <div style="display:flex;align-items: center;">
          <div style="margin-right:15px;">
            <el-input @input="keyWordSerach()" v-model="searchData.keyWord" size="small" placeholder="关键字搜索" />
          </div>
          <el-button-group style="margin-right:15px;">
            <el-button size="small" type="primary" icon="Search" @click="btnSearch()">查询</el-button>
            <el-button size="small" type="primary" icon="ArrowDownBold" @click="isshowdrawer = true"></el-button>
          </el-button-group>
          <el-button size="small" type="info" icon="Refresh" plain @click="reset()">重置</el-button>
          <!-- <el-button size="small" type="success" icon="CirclePlus" @click="addData()">新建</el-button> -->
          <!-- <el-button size="small" type="success" icon="CirclePlus" @click="openCanvasDialogFn()">绘制板</el-button> -->
        </div>
      </div>
    </el-header>
    <el-main>
      <el-table ref="tableRef" 
      height="100%"
      :data="tableData"
      :row-style="(e) => $store.state.tableRowStyle(e, rowStyle)"
      :header-cell-style="$store.state.outheaderstyle"
      @row-click="rowClick"
      @filter-change="filterChange" 
      @selection-change="handleSelectionChange" 
      @cell-dblclick="cellDBClick"
      @sort-change="sortChange"
      @row-contextmenu="rowContextMenu"
      row-key="id"
      size="small">
        <el-table-column type="selection"></el-table-column>
        <el-table-column prop="secretKey" label="密钥ID" width="180" 
          column-key="secretKey"
          show-overflow-tooltip>
        </el-table-column>
        <el-table-column prop="secretKeyType" label="密钥类型" width="100" show-overflow-tooltip
        column-key="secretKeyTypes"
        :filters="[
          { text: '黑锁', value: '0' },
          { text: '白锁', value: '1' }
        ]">
          <template #default="scope">
            <el-tag size="small" v-show="scope.row.secretKeyType == 0" type="success" effect="dark">黑锁</el-tag>
            <el-tag size="small" v-show="scope.row.secretKeyType == 1" type="info" effect="dark">白锁</el-tag>
          </template>
        </el-table-column>
        <el-table-column prop="bindSecretKey" label="配对密钥" show-overflow-tooltip width="140"></el-table-column>
        <el-table-column prop="useStatus" label="使用状态" 
          column-key="useStatus"
          :filters="[
            { text: '未使用', value: '0' },
            { text: '已使用', value: '1' }
          ]"
          show-overflow-tooltip>
          <template #default="scope">
            <el-tag size="small" v-show="scope.row.useStatus == 0" type="primary" effect="dark">未使用</el-tag>
            <el-tag size="small" v-show="scope.row.useStatus == 1" type="success" effect="dark">已使用</el-tag>
          </template>
        </el-table-column>
        <el-table-column prop="enterpriseName" label="企业名称" width="180" show-overflow-tooltip/>
        <el-table-column prop="entUserName" label="企业成员" width="180" show-overflow-tooltip/>
        <!-- <el-table-column prop="agentName" label="代理商名称" width="180" show-overflow-tooltip/> -->
        <el-table-column prop="agentUserName" label="分配成员" width="180" show-overflow-tooltip/>
        <!-- <el-table-column prop="enterpriseName" label="企业名称" 
          column-key="enterpriseName" width="180"
          show-overflow-tooltip>
        </el-table-column>
        <el-table-column prop="agentName" label="代理商名称" 
          column-key="agentName" width="180"
          show-overflow-tooltip>
        </el-table-column> -->
        <el-table-column prop="buyTime" label="购买时间" 
          column-key="buyTime"
          width="120"
          show-overflow-tooltip>
          <template #default="scope">
            {{ $filters.DateFilter(scope.row.buyTime, 'yyyy-MM-dd') }}
          </template>
        </el-table-column>

        <el-table-column align="center" width="200px" fixed="right" label="操作">
          <!-- <template #header>
            <el-input @input="keyWordSerach()" v-model="searchData.keyWord" size="small" placeholder="关键字搜索" />
          </template> -->
          <template #default="scope">
            <el-button size="small" @click="getBack([scope.row.id])">归还</el-button>
            <el-button size="small" @click="handleEdit(scope.$index, scope.row)">编辑</el-button>
            <el-button size="small" type="danger" @click="handleDelete(scope.row, 1)">删除</el-button>
          </template>
        </el-table-column>
      </el-table>
    </el-main>
    <el-footer>
      <div style="display: flex;align-items: center;height: 45px;">
        <div style="flex-grow: 1">
          <el-button size="small" style="" type="primary" @click="getBackIds()">归还</el-button>
          <el-button size="small" style="" type="danger" icon="Delete" @click.stop="deletechoose">批量删除</el-button>
        </div>
        <el-pagination
          size="small"
          v-model:currentPage="searchData.page"
          v-model:page-size="searchData.limit"
          :page-sizes="searchData.pageSizes"
          :background="true"
          layout="total, sizes, prev, pager, next, jumper"
          :total="searchData.totalItemCount"
          @size-change="handleSizeChange"
          @current-change="handleCurrentChange"
        />
      </div>
    </el-footer>
    <!-- =================================== 弹出层 ================================ -->
    <el-dialog custom-class="diyDialog" class="diyDialog" 
    v-model="openDialog" :before-close="(done) => beforeClose(done)" 
    destroy-on-close
    title="列表详情" width="1050px">
    
      <div class="contentbox_border border" :style="'max-height: ' + ($store.state.dialog_body_height) + 'px;overflow-y: auto;'">
        <data-detail v-if="dialogSwitch == 'data_detail'" ref="data_detail" @close-dialog="closeDialog"></data-detail>
      </div>
      
      <template #footer>
        <div class="dialog-footer">
          <el-button type="primary" @click="saveData()">保存</el-button>
          <el-button @click="clickClose()">关闭</el-button>
        </div>
      </template>

    </el-dialog>
    <!-- =========================================================================== -->

    <el-drawer
      v-model="isshowdrawer"
      title="高级筛选"
      direction="rtl"
      :before-close="drawerHandleClose"
    >
      <div class="flexbox" style="margin-bottom:10px;">
        <div class="searchContent">企业名称：</div>
        <div class="searchBox" style="width:100%;">
          <el-input placeholder="请输入企业名称" v-model="searchData.enterpriseName"></el-input>
        </div>
      </div>

      <template #footer>
        <div style="flex: auto">
          <el-button size="small" @click="isshowdrawer=false">关闭</el-button>
          <el-button size="small" type="info" icon="Refresh" @click="reset()">重置</el-button>
          <el-button size="small" type="primary" @click="btnSearch()">查询</el-button>
        </div>
      </template>
    </el-drawer>

    <!-- ====================================右键菜单================================== -->
    <context-menu-pop>
      <template #pop_body>
        <div style="cursor: pointer;padding:3px 0;font-size: 14px;">
          <div class="clickitem" @click="contextMenuClick()">
            <div class="itemleft">功能1</div>
            <div class="itemright"></div>
          </div>
          <div class="clickitem" @click="contextMenuClick()">
            <div class="itemleft">功能2</div>
            <div class="itemright"></div>
          </div>
          <div class="clickitem" @click="contextMenuClick()">
            <div class="itemleft">功能3</div>
            <div class="itemright"></div>
          </div>
          <div class="clickitem" @click="contextMenuClick()">
            <div class="itemleft">功能4</div>
            <div class="itemright"></div>
          </div>
        </div>
        
      </template>
    </context-menu-pop>


  </el-container>
</template>

<script setup>
  import DataDetail from './detail.vue'
  import ContextMenuPop from '@/components/Jm_ContextMenu/jm_popMenu.vue'

  // import useMixin from '@/assets/utils/useMixin'

  // console.log(useMixin())
  // const { mData } = useMixin()

  // console.log(mData)
  import { reactive, ref, onMounted, inject, nextTick } from 'vue'
  import { useStore } from 'vuex'
  // 注入全局utils工具js
  const $utils = inject('$utils')
  // 注入全局filters工具js
  const $filters = inject('$filters')
  // 定义store
  const store = useStore()
  // 设置行的颜色，空值为默认值
  const rowStyle = reactive({ id: '', color: '' })
  // 
  const dialogSwitch = ref('')

  // 定义子组件的ref
  const data_detail = ref()

  // 定义定时器
  const timmer = ref(null)

  // *********************************定义变量**********************************
  // 页眉
  const breadcrumb = ref(['密钥管理'])
  // 是否开启详细查询
  const isshowdrawer = ref(false)
  // 筛选条件分布
  const filterData = ref({
    userName: [
      { text: '测试1', value: '测试1' }, 
      { text: '测试2', value: '测试2' }
    ]
  })
  // 定义table的ref绑定
  const tableRef = ref()
  // 筛选条件
  const searchData = ref({
    page: 1,
    pageSizes: [30, 100, 200, 300, 400],
    limit: 30,
    totalItemCount: 100,
    keyWord: ''
  })
  // 批量选择的数据
  const chooseTableData = ref()
  // 初始化表格数据
  const tableData = ref([])
  // 是否开启弹窗
  const openDialog = ref(false)
  // ***************************************************************************

  // 进入该模块执行的方法
  const onMountedHook = function () {
    console.log('进入该modal模块执行的方法')
    if (store.state.isOldRouter || store.state.routerMode_refrash) {
      getData()
    }
  }

  // ****************************************************************************
  // ------------------ 右键菜单事件 ---------------------------
  function rowContextMenu(row, column, event) {
    // event.preventDefault()
    // // console.log(event)
    // // console.log(row)
    // // console.log(column)
    // rowStyle.id = row.id
    // store.commit('set_pop_attr', {
    //   pop_show: true, 
    //   get_event: event
    // })
  }
  // ----------------- 右键点击选择菜单事件 -------------------------
  function contextMenuClick() {
    store.commit('set_pop_attr', {
      pop_show: false
    })
  }
  // **************************************************************************

  // **************************************************************************

  // 保存数据提交方法
  function saveData() {
    data_detail.value.submitData()
  }
  // 输入关键字查询
  function keyWordSerach() {
    if (timmer.value) {
      clearTimeout(timmer.value)
    }
    timmer.value = setTimeout(() => {
      btnSearch()
    }, 300)
  }
  // 查询第一页数据方法
  function btnSearch() {
    searchData.value.page = 1
    getData()
  }
  // 获取数据方法
  function getData() {
    tableData.value = []
    $utils.post({
      url: '/Api/SecretKeyInfo/GetPageList',
      params: searchData.value,
      ok: function (res) {
        tableData.value = res.data
        searchData.value.totalItemCount = res.count
      }
    })
  }
  // 新建列表方法
  async function addData() {
    showView('data_detail')
    await nextTick()
  }
  
  function getBackIds () {
    var ids = []
    chooseTableData.value.forEach(item => {
      ids.push(item.id)
    })
    if (ids.length == 0) {
      $utils.$message({
        showClose: true,
        center: true,
        message: '请选择操作数据',
        type: 'warning'
      })
    } else {
      getBack(ids)
    }
  }

  function getBack(ids) {
    $utils.post({
      url: '/api/SecretKeyInfo/Restitution',
      params: {ids: ids},
      confirm: true,
      confirmText: '是否归还选中密钥？',
      confirmTitle: '提示',
      ok: function (data) {
        getData()
      }
    })
  }
  // 编辑数据方法
  async function handleEdit(index, item) {
    // 查询详情数据
    const res = await getPageData(item)
    if (res.data.code == 0) {
      // openDialog.value = true
      showView('data_detail')
      // 等待组件渲染完成
      await nextTick()
      data_detail.value.initData({
        data: res.data.data.model
      })
    }
  }
  // 删除数据方法
  function handleDelete(item, flag) {
    // 删除方法相应的字段
    const del_Id = 'id'
    const ids = []
    if (flag == 0) {
      item.forEach(item => {
        ids.push(item[del_Id])
      })
    } else {
      ids.push(item[del_Id])
    }
    // $utils.post({
    //   url: '/Api/SecretKeyInfo/DoBatchDelete',
    //   params: { id: ids },
    //   confirm: true,
    //   showLoading: true,
    //   ok: function (res) {
    //     getData()
    //   }
    // })
  }
  // 批量删除数据方法
  function deletechoose() {
    if (chooseTableData.value.length == 0) {
      $utils.message({
        showClose: true,
        center: true,
        message: '请选择操作数据',
        type: 'warning'
      })
    } else {
      handleDelete(chooseTableData.value, 0)
    }
  }
  function getPageData(item) {
    return $utils.post({
      url: '/Api/SecretKeyInfo/GetEdit',
      params: {
        id: item.id
      },
      showLoading: true,
      noasync: true
    })
  }
  // ====================== 关闭弹窗事件 ===========================
  // 筛选展示的弹窗组件
  function showView(type) {
    openDialog.value = true
    dialogSwitch.value = type
  }
  function beforeClose(done, flag) {
    if (flag || store.state.close_showtip) {
      $utils.showCloseTip(function () {
        done()
        getData()
      })
    } else {
      done()
      getData()
    }
  }
  function closeDialog() {
    openDialog.value = false
    getData()
  }
  function clickClose() {
    openDialog.value = false
  }
  // *******************************修改分页*******************************
  // 改变每页条数方法
  function handleSizeChange(val) {
    searchData.value.limit = val
    getData()
  }
  // 改变页数方法
  function handleCurrentChange(val) {
    searchData.value.page = val
    getData()
  }
  // **************************************************************

  // *******************************Table操作*******************************
  // 多选数据
  function handleSelectionChange(val) {
    chooseTableData.value = val
  }
  // 行单击事件
  function rowClick(row, column, e) {
    rowStyle.id = row.id
  }
  // 标题头筛选
  function filterChange(filters) {
    const key = Object.keys(filters)[0]
    searchData.value[key] = filters[key]
    getData()
  }
  // 行双击事件
  function cellDBClick(row, column, cell, event) {
    handleEdit(1, row)
  }
  // 排序筛选
  function sortChange(obj) {
    if (!obj.prop) {
      searchData.value.orderBy = ''
    } else {
      searchData.value.orderBy = obj.prop + ' ' + obj.order
    }
    getData()
  }
  // 重置查询条件方法
  function reset() {
    tableRef.value.clearFilter()
    searchData.value = $utils.resetForm(searchData.value)
  }
  // **************************************************************

  onMounted(() => {
    onMountedHook()
  })

</script>

<style scoped>
.el-container {
  height: 100%;
}
.el-header {
  background-color:#fff;
  border:1px solid #DDE2E8;
  border-bottom:none;
  border-radius: 5px 5px 0 0;
}
.el-main {
  padding: 0;
  background-color:#fff;
  border:1px solid #DDE2E8;
}
.el-footer {
  height:45px;
  border-radius: 0 0 5px 5px;
  background-color:#fff;
  border:1px solid #DDE2E8;
  border-top:none;
}
/* .diyDialog :deep(.el-dialog__body) {
  padding: 0 !important;
}  */
/deep/ .el-dialog__body {
  padding: 0 15px 0 15px !important;
}
/deep/ .el-dialog {
  margin: 30px auto 30px !important;
  overflow: hidden !important;
}
</style>